package com.njtoyo.taxi.admin.service.business.operation_rule.impl;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njtoyo.taxi.admin.mapper.master.entity.Driver;
import com.njtoyo.taxi.admin.mapper.master.entity.PrivateCallApplyRecord;
import com.njtoyo.taxi.admin.mapper.master.mapper.DriverMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.PrivacyNumberReportMapper;
import com.njtoyo.taxi.admin.rest.presenter.business.operation_rule.privacy_number_report.PrivacyNumberReportPagePresenter;
import com.njtoyo.taxi.admin.rest.wrapper.business.operation_rule.privacy_number_report.PrivacyNumberReportAddUpdateWrapper;
import com.njtoyo.taxi.admin.service.business.operation_rule.PrivacyNumberReportService;
import com.njtoyo.taxi.admin.utils.private_number.PrivateNumberClient;
import com.njtoyo.taxi.admin.utils.private_number.report.DriverApplyPrivateCallWrapper;
import com.njtoyo.taxi.entity.backend.AdminUser;
import com.taxi.entity.common.RestResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.MultiValueMap;

import java.util.Map;

@Service
public class PrivacyNumberReportServiceImpl extends ServiceImpl<PrivacyNumberReportMapper, PrivateCallApplyRecord> implements PrivacyNumberReportService {
    @Autowired
    private DriverMapper driverMapper;

    @Override
    public IPage<PrivacyNumberReportPagePresenter> page(Integer current, Integer size, Map<String, String> params) {
        Page<PrivacyNumberReportPagePresenter> page = new Page<>(current, size);

        IPage<PrivacyNumberReportPagePresenter> pageResult = baseMapper.getPage(page, params);

        return pageResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult add(PrivacyNumberReportAddUpdateWrapper wrapper, AdminUser adminUser) {
        PrivateCallApplyRecord record = new PrivateCallApplyRecord()
                .setIdNumber(wrapper.getIdNumber())
                .setState(0)
                .setDriverId(wrapper.getDriverId())
                .setScenePhoto(wrapper.getScenePhoto())
                .setPhoneNumber(wrapper.getPhoneNumber())
                .setOperator(adminUser.getName());

        String[] split = StrUtil.split(wrapper.getScenePhoto(), "base64,");
        Pair<Boolean, String> result = PrivateNumberClient.sendDriverApplyPrivateCall(new DriverApplyPrivateCallWrapper()
                .setIdNumber(wrapper.getIdNumber())
                .setDriverNumber(wrapper.getPhoneNumber())
                .setDriverName(wrapper.getDriverName())
                .setScenePhoto(split.length>1  ? split[1] : split[0]));
        if (!result.getKey()) {
            return RestResult.failed("隐私号码报备失败，失败原因：" + result.getValue());
        }
        baseMapper.insert(record);
        return RestResult.success();
    }

    @Override
    public PrivateCallApplyRecord selectByPhoneNumber(Long id, String phoneNumber) {
        LambdaQueryWrapper<PrivateCallApplyRecord> queryWrapper = Wrappers.<PrivateCallApplyRecord>lambdaQuery()
                .eq(PrivateCallApplyRecord::getPhoneNumber, phoneNumber);
        if (ObjectUtil.isNotNull(id)) {
            queryWrapper.not(i -> i.eq(PrivateCallApplyRecord::getId, id));
        }
        PrivateCallApplyRecord privateCallApplyRecord = baseMapper.selectOne(queryWrapper);
        return privateCallApplyRecord;
    }

    @Override
    public RestResult total() {
        int unLeaveCount = driverMapper.selectCount(Wrappers.<Driver>lambdaQuery()
                .eq(Driver::getIsLeave, 0));
        int applyCount = baseMapper.selectCount(null);
        int applyFailCount = baseMapper.selectCount(Wrappers.<PrivateCallApplyRecord>lambdaQuery()
                .eq(PrivateCallApplyRecord::getState, 1));

        return RestResult.success(Dict.create()
                .set("unLeaveCount", unLeaveCount)
                .set("applyCount", applyCount)
                .set("unApplyCount", unLeaveCount - applyCount)
                .set("applyFailCount", applyFailCount)
        );
    }

    @Override
    public RestResult getDetailById(String id) {
        PrivateCallApplyRecord record = baseMapper.selectById(id);
        if (ObjectUtil.isEmpty(record)) {
            return RestResult.failed("隐私号码报备记录不存在");
        }
        Driver driver = driverMapper.selectById(record.getDriverId());


        return RestResult.success(Dict.create()
                .set("id", record.getId())
                .set("driverName", driver.getName())
                .set("phoneNumber", record.getPhoneNumber())
                .set("idNumber", record.getIdNumber())
                .set("scenePhoto", record.getScenePhoto())
                .set("driverId", record.getDriverId())

        );
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult update(PrivacyNumberReportAddUpdateWrapper wrapper, AdminUser adminUser) {
        PrivateCallApplyRecord record = new PrivateCallApplyRecord()
                .setId(wrapper.getId())
                .setIdNumber(wrapper.getIdNumber())
                .setDriverId(wrapper.getDriverId())
                .setScenePhoto(wrapper.getScenePhoto())
                .setPhoneNumber(wrapper.getPhoneNumber())
                .setOperator(adminUser.getName());


        Pair<Boolean, String> result = PrivateNumberClient.sendDriverApplyPrivateCall(new DriverApplyPrivateCallWrapper()
                .setIdNumber(wrapper.getIdNumber())
                .setDriverNumber(wrapper.getPhoneNumber())
                .setDriverName(wrapper.getDriverName())
                .setScenePhoto(wrapper.getScenePhoto()));
        if (!result.getKey()) {
            return RestResult.failed("隐私号码报备失败，失败原因：" + result.getValue());
        }
        baseMapper.updateById(record);
        return RestResult.success();
    }

    @Override
    public IPage<PrivacyNumberReportPagePresenter> unApplyPage(Integer current, Integer size, Map<String, String> params) {
        Page<PrivacyNumberReportPagePresenter> page = new Page<>(current, size);
        IPage<PrivacyNumberReportPagePresenter> pageResult = baseMapper.unApplyPage(page, params);
        return pageResult;
    }
}
